<?php
#CHttpRequest::getUserHostAddress();
#Yii::app()->request->userHostAddress
class UpdateController extends AdminController {
    
    public function init() {
        if(!isset($_POST['Reviews'])) Yii::app()->user->setState('xuploadFiles', array());
    }
    
    private function addOrUpdate($id=0, $viewToRender, $modelClass, $redirectTo, $params = array()) {
        if($id) {
            $model = CActiveRecord::model($modelClass)->findByPk($id);
            if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        } else eval('$model = new '.$modelClass.'();');
        
        if(isset($_POST[$modelClass])) {
            $model->attributes = $_POST[$modelClass];
            if($model->save()) $this->redirect($redirectTo);
        }
        $this->render($viewToRender, CMap::mergeArray(array('model'=>$model), $params));
    }
    
    public function actionPartnerCat($id=0) {
        if($id) {
            $cats = CHtml::listData(PartnerCat::model()->findAll("catId <> $id and parentId=0"), 'catId', 'name');
            $sortData = PartnerCatRaiting::model()->findAllByAttributes(array('catId'=>$id));
            $commentRatings = PartnersAdRevRating::model()->findAllByAttributes(array('catId'=>$id));
        } else { 
            $cats = CHtml::listData(PartnerCat::model()->findAll("parentId=0"), 'catId', 'name');
            $sortData = $commentRatings = '';
        }
        $this->addOrUpdate($id, 'partnerCat', 'PartnerCat', array('default/partnerCat'), array('cats'=>$cats ,'sortData'=> $sortData, 'commentRatings'=>$commentRatings));
    }
        
    public function actionUser($id=0) {
        if($id) {
            $model = User::model()->findByPk($id);
            if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        } else $model = new User();
        if(isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if($model->save()) $this->redirect(array('default/user'));
        }
        $catsList = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where('parentId=0')->queryAll();
        if($id && $model->role == 'moder') {
            $forumsData = Yii::app()->db->createCommand()->select('*')->from('forum_moderator')->queryAll();
            $catIdArr = array();
            for($i=0; $i<count($forumsData); $i++) $catIdArr[] = $forumsData[$i]['catId'];
            $partnersList = Yii::app()->db->createCommand()->select('name, partnerid, catId')->from('partners')->where(array('in', 'catId', $catIdArr))->queryAll();
        }
        $this->render('user', array('model'=>$model, 'forumsData'=>!empty($forumsData) ? $forumsData : '', 'partnersList'=>!empty($partnersList) ? $partnersList : '', 'catsList'=>$catsList));
    }
    
    public function actionGroup($id=0) {
        $this->addOrUpdate($id, 'group', 'Group', array('default/group'));
    }
    
    public function actionPartner($id=0) {
        if($id) {
            $model = Partner::model()->findByPk($id);
            if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        } else $model = new Partner();
        if(isset($_POST['Partner'])) {
            $model->attributes = $_POST['Partner'];
            if($model->save()) $this->redirect(array('default/partner'));
        }
        $cats = PartnerCat::model()->findAll(array('condition'=>"parentId=0", 'select'=>'catId, name'));
        $allCats = PartnerCat::model()->findAll(array('select'=>'catId, name'));
        if($id) {
            $partnerData = Partner::model()->with('invite', 'relPartners', 'cat')->findByPk($id);
            $partnerData->fillDelegates();
            $partnerSubCats = Yii::app()->db->createCommand()->select('name, catId')->from('partners_cat')->where('`parentId`='.$partnerData->cat->catId)->queryAll();
            $selectedCatSubCats = Yii::app()->db->createCommand()->select('c.catId, c.name, r.stackInAdmin')->from('partners_sub_cat_rel r')->join('partners_cat c', 'c.catId=r.catId')->where('partnerId='.$id)->order('r.stackInAdmin asc')->queryAll();
            if(empty($selectedCatSubCats)) $sortParams = Yii::app()->db->createCommand()->select('cr.val as crval, cr.catRatingId, cr.type, cr.catId, pr.val')->from('partners_catraitings cr')->leftJoin('partners_ratings pr', 'pr.catRatingId=cr.catRatingId and partnerId='.$id)->where('catId='.$partnerData->catId)->order('catRatingId asc')->queryAll();
            else $sortParams = Yii::app()->db->createCommand()->select('cr.val as crval, cr.catRatingId, cr.type, cr.catId, pr.val')->from('partners_catraitings cr')->leftJoin('partners_ratings pr', 'pr.catRatingId=cr.catRatingId and partnerId='.$id)->where('catId='.$selectedCatSubCats[0]['catId'])->order('catRatingId asc')->queryAll();
            $ratingTextFields = Yii::app()->db->createCommand()->select('*')->from('partners_text_score')->where('partnerId='.$id)->queryAll();
            $partnerRelCats = Yii::app()->db->createCommand()->select('c.name, c.catId, r.val, r.relCatId')->from('partners_relcat r')->join('partners_cat c', 'c.catId=r.relCatId')->where('r.partnerid='.$id)->queryAll();
        }
        $this->render('partner', array('model'=>$model, 'cats'=>$cats, 'allCats'=>$allCats, 'partnerData'=>isset($partnerData) ? $partnerData : '', 'partnerSubCats'=>isset($partnerSubCats) ? $partnerSubCats : '', 'selectedCatSubCats'=> isset($selectedCatSubCats) ? $selectedCatSubCats : '', 'sortParams'=>isset($sortParams) ? $sortParams : '', 'ratingTextFields'=>!empty($ratingTextFields) ? $ratingTextFields : '', 'partnerRelCats'=>!empty($partnerRelCats) ? $partnerRelCats : ''));
    }
    
    public function actionNews($id=0) {
        if($id) {
            $model = News::model()->findByPk($id);
            if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        } else $model = new News();
        if(isset($_POST['News'])) {
            if($model->save()) $this->redirect(array('default/news'));
        }
        if($id) {
            $newsRelationsData = Yii::app()->db->createCommand()->select('c.catId, nr.partnerId')->from('news_relation nr')->join('partners_cat c', 'c.catId=nr.catId')->where('`newsId`='.$id)->queryAll();
            $catIdArr = array();
            foreach ($newsRelationsData as $item) $catIdArr[] = $item['catId'];
            $res = Yii::app()->db->createCommand()->select('c.catId, c.name as catName, p.name, p.partnerid')->from('partners p')->join('partners_cat c', 'c.catId=p.catId')->where(array('in', 'p.catId', $catIdArr))->queryAll();
        }
        $catsList = Yii::app()->db->createCommand()->select('name, catId')->from('partners_cat')->queryAll();
        $this->render('news', array('model'=>$model, 'catsList'=>$catsList, 'newsRelationsData'=>!empty($newsRelationsData) ? $newsRelationsData : '', 'res'=>!empty($res) ? $res : ''));
    }
    
    public function actionReview($id) {
        $model = Reviews::model()->with('user', 'images', 'revRatings', 'partner.cat')->findByPk($id);
        if(!$model) throw new CHttpException(404, 'Не найдено указанной записи'); 
        if($model->status == 'Новый') Yii::app()->db->createCommand()->update('reviews', array('status'=>'В работе'), 'revId='.$id);
        if(isset($_POST['Reviews'])) {
            $model->attributes = $_POST['Reviews'];
            if($model->save()) $this->redirect(array('default/redactor'));
        }
        $delegates = User::model()->findAll("userId IN(".$model->partner->delegate1.", ".$model->partner->delegate2.")");
        $revRatings = PartnersAdRevRating::model()->findAllByAttributes(array('catId'=>$model->partner->cat->parentId ? $model->partner->cat->parentId : $model->partner->cat->catId));
        $revTextRatings = Yii::app()->db->createCommand()->select('rt.val, ps.title, ps.about, ps.scoreId')->from('partners_text_score ps')->leftJoin('reviews_text_ratings rt', 'rt.scoreId=ps.scoreId and revId='.$id)->where('ps.partnerId='.$model->partner->partnerid)->queryAll();
        $this->render('review', array('model'=>$model, 'revRatings'=>$revRatings, 'delegates'=>$delegates, 'revTextRatings'=>$revTextRatings));
    }
    
    public function actionLogoMenu($id=0) {
        $this->addOrUpdate($id, 'logoMenu', 'LogoMenu', array('default/logoMenu'));
    }
    
    public function actionMainMenu($id=0) {
        $this->addOrUpdate($id, 'mainMenu', 'MainMenu', array('default/mainMenu'));
    }
    
    public function actionPage($id=0) {
        $this->addOrUpdate($id, 'page', 'Page', array('default/page'));
    }
    
    public function actionOption($id) {
        $this->addOrUpdate($id, 'option', 'Options', array('default/options'));
    }
    
    public function actionMailing($id=0) {
        $model = new Mailing();
        if(isset($_POST['Mailing'])) {
            if($model->save()) $this->redirect(array('default/mailing'));
        }
        $userEmails = CPartnerkiHelper::ArrToStr(User::model()->findAll(array('select'=>'email')), 'email');
        $subscribeEmails = CPartnerkiHelper::ArrToStr(Yii::app()->db->createCommand()->select('email')->from('subscribers')->where('`type`="partner" and userId>0')->queryAll(), 'email');
        $unregEmails = CPartnerkiHelper::ArrToStr(Yii::app()->db->createCommand()->select('email')->from('subscribers')->where('userId=0')->queryAll(), 'email');
        $unregDP = new CActiveDataProvider('Subscribers', array('pagination'=>array('pageSize'=>30), 'criteria'=>array('condition'=>'userId=0')));
        $subscrDP = new CActiveDataProvider('Subscribers', array('pagination'=>array('pageSize'=>30), 'criteria'=>array('condition'=>'`type`="partner" and userId>0')));
        $this->render('mailing', array('model'=>$model, 'subscrDP'=>$subscrDP, 'unregDP'=>$unregDP, 'userEmails'=>$userEmails, 'subscribeEmails'=>$subscribeEmails, 'unregEmails'=>$unregEmails));
    }
    
    public function actionBlogCat($id=0) {
        $this->addOrUpdate($id, 'blogCat', 'BlogCats', array('default/blogCat'));
    }
    
    public function actionBlogart($id=0) {
        if($id) {
            $model = BlogArts::model()->findByPk($id);
            if(!$model) throw new CHttpException(404, 'Не найдено указанной записи');
        } else $model = new BlogArts();
        if(isset($_POST['BlogArts'])) {
            if($model->save()) $this->redirect(array('default/blogArt'));
        }
        $blogCats = BlogCats::model()->findAll(array('select'=>'catId, name'));
        $this->render('blogArt', array('model'=>$model, 'blogCats'=>$blogCats));
    }
    
    public function actionBanIp($id=0){
        $this->addOrUpdate($id, 'banIp', 'BanIp', array('default/banIp'));
    }
    
    public function actionPartErr($id) {
        $this->render('partErr', array('messages'=>Yii::app()->db->createCommand()->select('e.login, p.name, p.url, e.email, e.text, c.catId, c.parentId')->from('error_reporting e')->join('partners p', 'p.partnerid=e.partnerId')->join('partners_cat c', 'c.catId=p.catId')->queryRow()));
    }
    
    public function actionKarmaParams($id=1) {
        $model = new KarmaParamsForm();
        if(isset($_POST['KarmaParamsForm'])) {
            if($model->validate()) {
                Yii::app()->db->createCommand()->update('karma_params', $_POST['KarmaParamsForm']);
                Yii::app()->db->createCommand()->delete('karma_levels');
                if(!empty($_POST['KarmaLevels'])) {
                    for($i=0; $i<count($_POST['KarmaLevels']['karma']); $i++) {
                        if(empty($_POST['KarmaLevels']['weight'][$i])) continue;
                        Yii::app()->db->createCommand()->insert('karma_levels', array('carma'=>$_POST['KarmaLevels']['karma'][$i], 'weight'=>$_POST['KarmaLevels']['weight'][$i]));
                    }
                }
                $this->redirect(array('default/karmaParams'));
            }
        }
        $karmaLevels = Yii::app()->db->createCommand()->select('*')->from('karma_levels')->order('carma asc')->queryAll();
        $karmaData = Yii::app()->db->createCommand()->select('*')->from('karma_params')->where('id='.$id)->queryRow();
        $this->render('karmaParams', array('model'=>$model, 'karmaData'=>$karmaData, 'karmaLevels'=>$karmaLevels));
    }
    
    public function actionBanUser($id=0) {
        $model = new BanUserForm();
        if(isset($_POST['BanUserForm'])) {
            if($model->validate()) {
                if($id) Yii::app()->db->createCommand()->update('users', array('isBanned'=>$model->isBanned, 'unblockDate'=>$model->unblockDate), "userid=$id");
                else Yii::app()->db->createCommand()->update('users', array('isBanned'=>$model->isBanned, 'unblockDate'=>$model->unblockDate), "login=\"$model->login\"");
                $this->redirect(array('default/banUser'));
            }
        }
        if($id) {
            $userData = Yii::app()->db->createCommand()->select('login, isBanned, unblockDate')->from('users')->where('userid='.$id)->queryRow();
            if(empty($userData)) throw new CHttpException(404);
        } 
        $this->render('banUser', array('model'=>$model, 'userData'=>!empty($userData) ? $userData : ''));
    }
    
    public function actionBrending($id=0) {
        if($id) {
            $model = Brending::model()->findByPk($id);
            if(!$model) throw new CHttpException(404);
        } else $model = new Brending();
        if(isset($_POST['Brending'])) {
            $model->attributes = $_POST['Brending'];
            $butImg = CUploadedFile::getInstance($model, 'butImg');
            if(!empty($butImg)) $model->setScenario('uploadBut');
            if($model->validate()) {
                if(!empty($butImg)) {
                    $model->butImg = md5( rand(0,10000) . $butImg->getName() . microtime() ).'.'.$butImg->getExtensionName();
                    $butImg->saveAs(Yii::getPathOfAlias('webroot').'/images/uploads/brending/'.$model->butImg);
                }
                $bgImg = CUploadedFile::getInstance($model, 'bgImg');
                if(!empty($bgImg)) {
                    $model->bgImg = md5( rand(0,10000) . $bgImg->getName() . microtime() ).'.'.$bgImg->getExtensionName();
                    $bgImg->saveAs(Yii::getPathOfAlias('webroot').'/images/uploads/brending/'.$model->bgImg);
                }
                $model->save(false);
                $this->redirect(array('default/brending'));
            } 
        }
        if($id) {
            if($model->type == 'partner')
                $data = Yii::app()->db->createCommand()->select('partnerid as id, name')->from('partners')->queryAll();
            elseif($model->type == 'cat') $data = Yii::app()->db->createCommand()->select('catId as id, name')->from('partners_cat')->queryAll();
        }
        $this->render('brending', array('model'=>$model, 'data'=>!empty($data) ? $data : ''));
    }
    
    public function actionSponsorAdt($id=0) {
        if($id) {
            $model = Banners::model()->findByPk($id);
            if(!$model) throw new CHttpException(404);
        } else $model = new Banners();
        if(isset($_POST['Banners'])) {
            if($model->save()) $this->redirect (array('default/sponsorAdt'));
        }
        if($id) $relData = Yii::app()->db->createCommand()->select('catId')->from('banners_relations')->where('bannerId='.$id)->queryAll();
        $cats = Yii::app()->db->createCommand()->select('name, catId')->from('partners_cat')->where('parentid=0')->queryAll();
        $this->render('sponsorAdt', array('relData'=>!empty($relData) ? $relData : '', 'cats'=>$cats, 'model'=>$model));
    }
    
    public function actionBannersBig($id=0) {
        $this->addOrUpdate($id, 'bannersBig', 'BannersBig', array('default/bannersBig'));
    }
}